import Flutter
import UIKit

public class ProxyCheckPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "proxy_check", binaryMessenger: registrar.messenger())
    let instance = ProxyCheckPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "getPlatformVersion":
      result("iOS " + UIDevice.current.systemVersion)
     case "checkProxy":
        checkProxy(result)
    default:
      result(FlutterMethodNotImplemented)
    }
  }

  private func checkProxy(result:@escaping FlutterResult){
  let isProxy = hasProxy()
  result(isProxy)
  }

private func hasProxy() -> Bool {
  let proxySettings = CFNetworkCopySystemProxySettings()?.takeRetainedValue() as? [AnyHashable: Any]
  let proxies = proxySettings?["__SCOPED__"] as? [Any] ?? []
  for proxy in proxies {
    if let proxyDict = proxy as? [AnyHashable: Any],
       let host = proxyDict["HTTPPROXY_HOST"] as? String, !host.isEmpty,
       let port = proxyDict["HTTPPROXY_PORT"] as? Int, port > 0 {
      return true
    }
  }
  return false
}

}
